package com.hy.service.impl;

import ch.qos.logback.core.pattern.color.MagentaCompositeConverter;
import com.google.gson.Gson;
import com.hy.config.constants.WeChatContant;
import com.hy.entitys.StoryEntity;
import com.hy.entitys.weChatInfo.ArticleItem;
import com.hy.entitys.weChatInfo.ReqMessage_Base;
import com.hy.entitys.weChatInfo.ReqMessage_Text;
import com.hy.mapper.StoryMapper;
import com.hy.service.IStoryService;
import com.hy.service.StoryService;
import com.hy.service.WeChatService;
import com.hy.utils.RobotUtils;
import com.hy.utils.WxUtils;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Service
public class WeChatServiceImpl implements WeChatService {

    Log logger = LogFactory.getLog(WeChatServiceImpl.class);

    @Autowired
    public IStoryService storyService;
    @Autowired
    private StoryService istorageService;



    public String processRequest(HttpServletRequest request) {
        // xml格式的消息数据
        String respXml = null;
        // 默认返回的文本消息内容
        String respContent;
        try {
            // 调用parseXml方法解析请求消息
            Map<String,String> requestMap = WxUtils.parseXml(request);
            // 消息类型
            String msgType = (String) requestMap.get(WeChatContant.MsgType);
            String mes = null;
            // 文本消息
            if (msgType.equals(WeChatContant.REQ_MESSAGE_TYPE_TEXT)) {
                mes =requestMap.get(WeChatContant.Content).toString();
                if(mes!=null){
                    //更新小说关键字
                    if(mes.contains("更新小说-")){
                        //分割请求内容
                        String[] split = mes.split("-");
                        //定义回复内容
                        StringBuffer content = new StringBuffer();
                        //根据小说名查找小说
                        List<StoryEntity> storys = storyService.findStory(split[split.length - 1]);

                        if (storys.isEmpty()){

                        }else {
                            StoryEntity story = storys.get(0);
                            content.append("正在为您跟新并压缩小说:"+story.getName());
                            content.append("\n作者:"+story.getAuthor());
                            content.append("\n最后更新时间:"+story.getUpdateTime());
                            content.append("\n有些小说内容较大可关闭公众号,过段时间再来下载");
                            Runnable runner = ()->{
                                logger.info("----------------开始跟新小说:"+story.getName()+"----------------");
                                String msg = istorageService.saveStoryAll(story);
                                if ("".equals(msg)){
                                    content.append("\n您要跟新的小说正在跟新请稍候再试");
                                }else {
                                    logger.info("----------------更新完毕小说:"+story.getName()+"----------------");
                                }
                            };
                            new Thread(runner).start();

                        }
                        ReqMessage_Text reqMessage_text = new ReqMessage_Text();
                        reqMessage_text.setToUserName(requestMap.get(WeChatContant.FromUserName));
                        reqMessage_text.setFromUserName(requestMap.get(WeChatContant.ToUserName));
                        reqMessage_text.setMsgType("text");
                        reqMessage_text.setCreateTime(new Date().getTime());
                        reqMessage_text.setContent(content.toString());
                        respXml = WxUtils.entityToXML(reqMessage_text);

                    }
                    //下载小说关键字
                    if (mes.contains("下载小说-")){
                        //分割请求内容
                        String[] split = mes.split("-");
                        //定义回复内容
                        StringBuffer content = new StringBuffer();
                        //根据小说名查找小说
                        String name=split[split.length - 1];
                        List<StoryEntity> storys = istorageService.selectStoryByName(name);

                            if (storys.size()!=1){
                                logger.error("数据库错误请查证:"+name);
                                content.append("小说名错误或数据库中没有");
                            }else {
                                StoryEntity story = storys.get(0);
                                if(story.getStatus()==1){
                                    content.append("小说名:"+story.getName());
                                    content.append("\n作者:"+story.getAuthor());
                                    content.append("\n最后更新时间:"+story.getUpdateTime());
                                    content.append("\n下载地址:"+story.getSaveUrl());

                                }else if (story.getStatus()==0){
                                    content.append("该小说正在更新中请稍后");

                                }else {
                                    content.append("数据库中不存在您要下载的小说,请先更新小说");

                                }

                            }
                            ReqMessage_Text reqMessage_text = new ReqMessage_Text();
                            reqMessage_text.setToUserName(requestMap.get(WeChatContant.FromUserName));
                            reqMessage_text.setFromUserName(requestMap.get(WeChatContant.ToUserName));
                            reqMessage_text.setMsgType("text");
                            reqMessage_text.setCreateTime(new Date().getTime());
                            reqMessage_text.setContent(content.toString());
                            respXml = WxUtils.entityToXML(reqMessage_text);


                    }


                }else{
                   /* Map<String, String> userInfo = getUserInfo(requestMap.get(WeChatContant.FromUserName));
                    System.out.println(userInfo.toString());
                    String nickname = userInfo.get("nickname");
                    String city = userInfo.get("city");
                    String province = userInfo.get("province");
                    String country = userInfo.get("country");
                    String headimgurl = userInfo.get("headimgurl");
                    List<ArticleItem> items = new ArrayList<>();
                    ArticleItem item = new ArticleItem();
                    item.setTitle("你的信息");
                    item.setDescription("昵称:"+nickname+"  地址:"+country+" "+province+" "+city);
                    item.setPicUrl(headimgurl);
                    item.setUrl("http://www.baidu.com");
                    items.add(item);

                    respXml = WxUtils.sendArticleMsg(requestMap, items);*/
                }
            }
            // 图片消息
            else if (msgType.equals(WeChatContant.REQ_MESSAGE_TYPE_IMAGE)) {
                respContent = "您发送的是图片消息！";
                respXml = WxUtils.sendTextMsg(requestMap, respContent);
            }
            // 语音消息
            else if (msgType.equals(WeChatContant.REQ_MESSAGE_TYPE_VOICE)) {
                respContent = "您发送的是语音消息！";
                respXml = WxUtils.sendTextMsg(requestMap, respContent);
            }
            // 视频消息
            else if (msgType.equals(WeChatContant.REQ_MESSAGE_TYPE_VIDEO)) {
                respContent = "您发送的是视频消息！";
                respXml = WxUtils.sendTextMsg(requestMap, respContent);
            }
            // 地理位置消息
            else if (msgType.equals(WeChatContant.REQ_MESSAGE_TYPE_LOCATION)) {
                respContent = "您发送的是地理位置消息！";
                respXml = WxUtils.sendTextMsg(requestMap, respContent);
            }
            // 链接消息
            else if (msgType.equals(WeChatContant.REQ_MESSAGE_TYPE_LINK)) {
                respContent = "您发送的是链接消息！";
                respXml = WxUtils.sendTextMsg(requestMap, respContent);
            }
            // 事件推送
            else if (msgType.equals(WeChatContant.REQ_MESSAGE_TYPE_EVENT)) {
                // 事件类型
                String eventType = (String) requestMap.get(WeChatContant.Event);
                // 关注
                if (eventType.equals(WeChatContant.EVENT_TYPE_SUBSCRIBE)) {
                    respContent = "谢谢您的关注！";
                    respXml = WxUtils.sendTextMsg(requestMap, respContent);
                }
                // 取消关注
                else if (eventType.equals(WeChatContant.EVENT_TYPE_UNSUBSCRIBE)) {
                    // TODO 取消订阅后用户不会再收到公众账号发送的消息，因此不需要回复
                }
                // 扫描带参数二维码
                else if (eventType.equals(WeChatContant.EVENT_TYPE_SCAN)) {
                    // TODO 处理扫描带参数二维码事件
                }
                // 上报地理位置
                else if (eventType.equals(WeChatContant.EVENT_TYPE_LOCATION)) {
                    // TODO 处理上报地理位置事件
                }
                // 自定义菜单
                else if (eventType.equals(WeChatContant.EVENT_TYPE_CLICK)) {
                    // TODO 处理菜单点击事件
                }
            }
            //调用机器人
            RobotUtils robotUtils = new RobotUtils();
            String msg = robotUtils.getMsg(mes);
            if(!"请求次数超限制!".equals(msg)){
                mes=msg;
            }else {
                mes="小阳机器人今天下班了,不能陪您聊天了";
            }


            mes = mes == null ? "不知道你在干嘛" : mes;

            if(respXml == null)
                respXml = WxUtils.sendTextMsg(requestMap, mes);
            return respXml;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";

    }
}
